const { defineConfig } = require('@vue/cli-service')
const path = require('path')
function resolve(dir) {
  return path.join(__dirname, dir)
}
const CompressionWebpackPlugin = require('compression-webpack-plugin') // 开启gzip压缩， 按需引用

const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)
// 本地环境是否需要使用cdn
const devNeedCdn = true
let cdn = { externals: {}, css: [], js: [] }
if (IS_PROD || devNeedCdn) {
  cdn = {
    externals: { 'element-ui': 'ELEMENT', vue: 'Vue', 'vue-router': 'VueRouter', axios: 'axios' },
    css: ['https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.14/theme-chalk/index.min.css'],
    js: [
      'https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js',
      'https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.14/index.min.js',
      'https://cdn.bootcdn.net/ajax/libs/vue-router/3.6.5/vue-router.min.js',
      'https://unpkg.com/axios/dist/axios.min.js'
    ]
  }
}

// 压缩代码并去掉console
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = defineConfig({
  transpileDependencies: true,
  publicPath: './',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  indexPath: 'index.html',
  productionSourceMap: false,
  configureWebpack: (config) => {
    const plugins = []
    if (IS_PROD) {
      // gzip压缩代码
      plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path][base].gz',
          algorithm: 'gzip',
          // 要压缩的文件（正则）
          test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
          // 最小文件开启压缩
          threshold: 10240,
          minRatio: 0.8
        })
      )
      plugins.push(
        // 压缩js
        new UglifyJsPlugin({
          uglifyOptions: {
            compress: {
              // 配置压缩选项，默认为true
              unused: true, // 是否移除没有引用的代码，默认为`true`
              dead_code: true, // 是否移除没有执行的代码，默认为`true`
              drop_console: true, // 删除所有调式带有console的
              drop_debugger: true,
              pure_funcs: ['console.log'] // 删除con
            },
            mangle: true, // 是否混淆代码
            output: {
              beautify: false, // 是否美化代码
              comments: false // 是否删除代码中的注释，默认为`true`
            }
          }
        })
      )
    }
    config.plugins = [...config.plugins, ...plugins]
  },
  chainWebpack: (config) => {
    config.resolve.alias // 添加别名
      .set('@', resolve('src'))
      .set('@assets', resolve('src/assets'))
      .set('@components', resolve('src/components'))
      .set('@views', resolve('src/views'))
      .set('@store', resolve('src/store'))
    // 移除 prefetch 插件
    config.plugins.delete('prefetch')
    // 移除 preload 插件
    config.plugins.delete('preload')
    // 压缩代码
    config.optimization.minimize(true)

    // externals 是 webpack 的一个配置项，用于声明那些不应该被 webpack 打包进最终 bundle 的库
    config.externals(cdn.externals)
    // 通过 html-webpack-plugin 将 cdn 注入到 index.html 之中
    config.plugin('html').tap((args) => {
      args[0].cdn = cdn
      return args
    })
  },
  devServer: {
    host: '127.0.0.1',
    hot: true,
    port: 8081,
    open: true,
    compress: true
  }
})
